layui.use(['form', 'jquery', 'layer', 'table', 'laydate', 'upload'], function() {
	var form = layui.form;
	var $ = layui.$;
	var table = layui.table;
	var layer = layui.layer;
	var laydate = layui.laydate;
	var upload = layui.upload;

	var lay_filter = 'tpl_brandcert' + id;
	form.val(lay_filter, brandcert_form_value);
	
	$('#brand_div_'+id).val(brandcert_form_value.brand_name)

	// 初始化分类和地区
	if (brandcert_form_value.category_arrs) {
		category_arr = brandcert_form_value.category_arrs
	}
	if (brandcert_form_value.area_arr) {
		area_arr = brandcert_form_value.area_arr
	}
	
	if(brandcert_form_value.channel){
		channel_arr = brandcert_form_value.channel;
	}

	// 初始化文件和证书
	if (brandcert_form_value.files) {
		for (var i in brandcert_form_value.files) {
			var html = createUploadHtmlSrc('files[]', brandcert_form_value.files[i]);
			$('#layui-upload-files' + id).append(html);
		}
	}
	if (brandcert_form_value.certs) {
		for (var i in brandcert_form_value.certs) {
			var html = createUploadHtmlSrc('certs[]', brandcert_form_value.certs[i]);
			$('#layui-upload-cert' + id).append(html);
		}
	}

	// 上传授权文件
	upload.render({
		elem: '#files_upload' + id,
		url: upload_uri,
		auto: true,
		field: 'files_upload' + id,
		accept: 'file',
		multiple: true,
		before: function(obj) {
			layer.load();
		},
		done: function(res, index, upload) {
			if (res.code == 0) {
				var item = this.item
				var html = createUploadHtmlSrc('files[]', res.data);
				item.prev('.layui-upload-list-files').append(html);
				layer.msg('上传成功', {
					icon: 1
				});
			} else {
				layer.msg(e.msg, {
					icon: 2
				});
			}

			layer.closeAll('loading');
		},
		error: function(index, upload) {
			layer.msg('网络错误', {
				icon: 2
			});
			layer.closeAll('loading');
		}
	});
	// 上传注册商标
	upload.render({
		elem: '#cert_upload' + id,
		url: upload_uri,
		auto: true,
		field: 'cert_upload' + id,
		accept: 'file',
		multiple: true,
		before: function(obj) {
			layer.load();
		},
		done: function(res, index, upload) {
			if (res.code == 0) {
				var item = this.item
				var html = createUploadHtmlSrc('certs[]', res.data);
				item.prev('.layui-upload-list-cert').append(html);
				layer.msg('上传成功', {
					icon: 1
				});
			} else {
				layer.msg(e.msg, {
					icon: 2
				});
			}

			layer.closeAll('loading');
		},
		error: function(index, upload) {
			layer.msg('网络错误', {
				icon: 2
			});
			layer.closeAll('loading');
		}
	});



	laydate.render({
		elem: 'input[name="start_date"]'
	});
	laydate.render({
		elem: 'input[name="end_date"]'
	});

	if (brandcert_form_value.channel != undefined) {
		$("input:checkbox[lay-filter='channel']").each((i) => {
			let e = $("input:checkbox[lay-filter='channel']:eq(" + i + ")");
			if (brandcert_form_value.channel.indexOf(e.val()) != -1) {
				e.attr('checked', true)
			}
		})
	}


	form.render('checkbox');

	//******************品牌搜索开始*************************//
	var get_brand_div = function(key) {
		var e = $('#brand_' + id);
		e.html('');
		var post_data = {
			brand_name: key
		};
		send_info(brand_select_uri, post_data, function(data) {
			e.html('<dd class="dd-class" lay-value="">请选择</dd>');
			if (data.count > 0) {
				for (var i in data.data) {
					var temp = data.data[i];
					let op_html = '<dd class="dd-class" lay-value="' + temp + '">' + temp + '</dd>'
					e.append(op_html);
				}
			};
		})
	}
	get_brand_div('')

	$('#brand_' + id).on('click', '.dd-class', function() {
		$('#brand_div_' + id).val($(this).attr('lay-value'));
		$('input[name="brand_name"]').val($(this).attr('lay-value'));
	})

	// 搜索分类
	$('#brand_div_' + id).on('input propertychange', function() {
		if ($(this).prop('comStart')) return;
		get_brand_div($(this).val())
	}).on('compositionstart', 'input[type="text"]', function() {
		$(this).prop('comStart', true);
	}).on('compositionend', 'input[type="text"]', function() {
		$(this).prop('comStart', false);
		$(this).trigger('input');
	}).on('focus', function() {
		$('#brand_' + id).show()
	}).on('blur', function() {
		setTimeout(function() {
			$('#brand_div_' + id).val($('input[name="brand_name"]').val());
			$('#brand_' + id).hide()
		}, 150);
	})

	//******************品牌搜索结束*************************//

	//******************分类联动开始************************//
	var get_goods_category = function(parent_sign, filter, value) {
		var e = $('form[lay-filter="' + lay_filter + '"]').find('#' + filter);
		e.html('');
		e.append('<option value="">加载中...</option>');
		e.prop('disabled', true);
		var id = e.attr('id');
		form.render('select');
		var post_data = {
			parent_sign: parent_sign,
			audit_state: 1
		}
		send_info(category_select_uri, post_data, function(data) {
			e.html('<option value="">请选择分类</option>');
			for (var i in data.data) {
				var temp = data.data[i];
				if (value == temp.category_sign) {
					var op_html = '<option selected value="' + temp.category_sign + '">' + temp
						.category_name + '</option>';
				} else {
					var op_html = '<option value="' + temp.category_sign + '">' + temp
						.category_name + '</option>';
				}
				e.append(op_html);
			}
			e.prop('disabled', false);
			form.render('select');
			if (value != undefined) {
				if (id == 'category_level1_' + id) {
					get_goods_category(value, 'category_level2_' + id, goods_form_value
						.category_sign2);
					$('form[lay-filter="' + lay_filter + '"]').find('#category_level3_' +
						id).html('');
				} else if (id == 'category_level2_' + id) {
					get_goods_category(value, 'category_level3_' + id, goods_form_value
						.category_sign3);
				} else {
					category_sign = value;
				}
			}
		})
	}
	var fliter1 = 'category_level1_' + id;
	// 分类联动
	form.on('select(category_level1_' + id + ')', function(data) {
		var value = data.value;
		var e = data.elem;
		get_goods_category(value, 'category_level2_' + id, '');
		$('form[lay-filter="' + lay_filter + '"]').find('#category_level3_' + id).html('');
	})
	form.on('select(category_level2_' + id + ')', function(data) {
		var value = data.value;
		var e = data.elem;
		get_goods_category(value, 'category_level3_' + id, '');
	})
	form.on('select(category_level3_' + id + ')', function(data) {
		var value = data.value;
		var e = data.elem;
		if (value) {
			// 移除全品类
			category_arr = category_arr.filter((item) => item.category_name !== '全品类');
			$('input:checkbox[name="all_category"]').attr('checked', false)
			form.render('checkbox');
			// 赋值
			category_sign = value;
			let flag = false;
			for (let i = 0; i < category_arr.length; i++) {
				if (category_arr[i].category_sign == value) {
					flag = true
				}
			}
			if (!flag) {
				let temp = {
					category_sign: value,
					category_name: $(this).context.innerText
				}
				console.log(category_arr.indexOf(temp))
				category_arr.push(temp)
				createCategoryDiv()
			}
		}
	})
	get_goods_category(0, 'category_level1_' + id, '');
	//******************分类联动结束************************//

	//******************授权分类开始*************************//
	// 生成选择div
	var createCategoryDiv = () => {
		$('.category-view_' + id).html('')
		category_arr.forEach((e, i) => {
			let temp = `<span class="category-delete">${e.category_name}<a style="margin-left:6px" class="layui-btn layui-btn-danger layui-btn-xs" lay-value="${e.category_name}"><i
					class="layui-icon layui-icon-delete"></i></a></span>`;
			$('.category-view_' + id).append(temp)
		})
	}
	
	createCategoryDiv()

	// 点击全品类按钮
	form.on('checkbox(all_category)', (data) => {
		if (data.elem.checked) {
			category_arr = [];
			category_arr.push({
				category_name: '全品类',
				category_sign: 'all'
			})
			createCategoryDiv()
		}
	})

	// 点击删除按钮
	$('.category-view_' + id).on('click', '.layui-btn-xs', function() {
		let del_val = $(this).attr('lay-value');
		category_arr = category_arr.filter((val) => {
			return val.category_name != del_val;
		})
		createCategoryDiv()
	})

	//******************授权分类结束*************************//



	//******************授权地区开始*************************//
	var get_area_div = function() {
		var e = $('select[name="select_city_' + id + '"]');
		e.html('');
		var post_data = {};
		send_info(area_select_uri, post_data, function(data) {
			e.html('<option value="">请选择</option><option value="全国">全国</option>');
			if (data.count > 0) {
				for (var i in data.data) {
					var temp = data.data[i];
					let op_html = '<option value="' + temp + '">' + temp + '</option>'
					e.append(op_html);
				}
			};
			form.render('select');
			form.on('select(select_city_' + id + ')', (res) => {
				if (res.value == '') {
					return false;
				}
				if (res.value == '全国') {
					area_arr = [];
				} else {
					area_arr = area_arr.filter((e) => {
						return e != '全国'
					})
				}
				area_arr.push(res.value)
				// 去重
				area_arr = area_arr.filter((item, index) => area_arr.indexOf(item) ===
					index);
				$('input[name="area"]').val(area_arr.join(','))
				createAreaDiv()
			})
		})
	}
	get_area_div()

	var createAreaDiv = () => {
		$('.area-view_' + id).html('')
		area_arr.forEach((e, i) => {
			let temp = `<span class="category-delete">${e}<a style="margin-left:6px" class="layui-btn layui-btn-danger layui-btn-xs" lay-value="${e}"><i
					class="layui-icon layui-icon-delete"></i></a></span>`;
			$('.area-view_' + id).append(temp)
		})
	}
	createAreaDiv()

	$('.area-view_' + id).on('click', '.layui-btn-xs', function() {
		let del_val = $(this).attr('lay-value');
		area_arr = area_arr.filter((val) => {
			return val != del_val;
		})
		$('input[name="area"]').val(area_arr.join(','))
		createAreaDiv()
	})


	//******************授权地区结束*************************//
	
	// 授权渠道
	form.on('checkbox(channel)',(data)=>{
		if(data.elem.checked){
			channel_arr.push(data.value)
		} else {
			channel_arr = channel_arr.filter((item)=>item != data.value)
		}
	})

	// 监听提交
	form.on('submit(submit_brandcert)', function(data) {
		var field = data.field;
		var temp = [];
		category_arr.forEach((e) => {
			temp.push(e.category_sign)
		})
		field.category_arr = temp.join(',');
		var url = $('form[lay-filter="tpl_brandcert' + id + '"]').attr('action');
		if (field.brand_name == '') {
			layer.msg('请选择品牌', {
				icon: 2,
				amim: 6
			})
			$('#brand_div_' + id).addClass('.layui-form-danger').focus();
			return false;
		}
		if ($('#layui-upload-files' + id).find('span').length == 0) {
			layer.msg('请上传授权文件', {
				icon: 2,
				amim: 6
			})
			return false;
		}
		/* if($('#layui-upload-cert'+id).find('span').length == 0){
			layer.msg('请上传商标注册证', {
				icon: 2,
				amim: 6
			})
			return false;
		} */

		if (field.category_arr == '') {
			layer.msg('请选择授权品类范围', {
				icon: 2,
				amim: 6
			})
			$('#brandcert_div_' + id).addClass('.layui-form-danger').focus();
			return false;
		}
		if (field.area == '') {
			layer.msg('请选择授权区域', {
				icon: 2,
				amim: 6
			})
			$('select[name="select_city_' + id + '"]').addClass('.layui-form-danger').focus();
			return false;
		}
		if (field.levels == '区域授权' || field.levels == '项目授权' || field.levels == '其他（多级）') {
			if (field.levels_intro == '') {
				layer.msg('区域授权或项目授权请输入分级补充', {
					icon: 2,
					amim: 6
				})
				$('input[name="levels_intro"]').addClass('.layui-form-danger').focus();
				return false;
			}
		}
		if(channel_arr.length == 0){
			layer.msg('请选择授权渠道', {
				icon: 2,
				amim: 6
			})
			return false;
		}
		send_info(url, field, function(data) {
			if (data.code == 0) {
				layer.msg('保存成功', {
					icon: 1
				});
				// 关闭当前页 刷新父页
				$('.layui-body .layui-tab[lay-filter="content"] li.layui-this .layui-tab-close')
					.trigger('click');
				$('.layui-body .layui-tab[lay-filter="content"] li[lay-id="brandcert"]')
					.trigger(
						'click');
				// 父页面点击
				$('.layui-body .layui-tab[lay-filter="content"] li[lay-id="brandcert_list"]')
					.trigger('click');
				// 表格重载
				table.reload('brandcert_list');
			} else {
				layer.msg(data.msg, {
					icon: 2,
					anim: 6
				});
			}
		})
		return false;
	})



})